<?php
namespace Wap\Model;
use Think\Model;

class PraiseItemRecordModel extends Model//TODO: 代码优化
{
	protected $tableName = "praise_record2";
	public static $token_arr = ["wfupsi1535969682", "bfozsi1569808457"];
	public function insert( $datas )
	{
		$result = array( "success"	=>	false,	"data"	=>	array() );

		//$this->startTrans();
		$id = $this->data( $datas )->add();//增加一条点赞记录

		$mode = D( "praiseItem" );
		$updated_votes = $mode->update_votes( $datas['pid'] );//更新本作品的票数、排名、票数差

		if( $id && $updated_votes ){
			//$this->commit();
			$result['success'] = true;
			$result['data'] = $mode->fetch_rank_by_id( $datas['pid'], $datas['praise'] );
		}else{
			//$this->rollback();
		}

		return $result;
	}

    public function eatinsert( $datas )
    {
        $result = array( "success"	=>	false,	"data"	=>	array() );

        //$this->startTrans();
        $id = $this->data( $datas )->add();//增加一条点赞记录

        $mode = D( "praiseItem" );
        $updated_votes = $mode->eat_update_votes( $datas['pid'] );//更新本作品的票数、排名、票数差

        if( $id && $updated_votes ){
            //$this->commit();
            $result['success'] = true;
            $result['data'] = $mode->fetch_rank_by_id( $datas['pid'], $datas['praise'] );
        }else{
            //$this->rollback();
        }

        return $result;
    }
	public function fetch_openid_votes( $openid = "", $praise, $begin_time = 0, $end_time = 0 )
	{
		$count	=	0;

		if( $end_time - $begin_time > 0 ){
			$count = $this->distinct(true)->field('openid')->where( "openid = '%s' AND praise = %d AND updated_time > %d AND updated_time < %d", array( $openid, $praise, $begin_time, $end_time ) )
				->count();
		}else if( $end_time - $begin_time < 0 && $end_time == 0 ){
			$count	=	$this->ditinct(true)->field(true)->where( "openid = '%s' AND praise = %d AND updated_time > %d", array( $openid, $praise, $begin_time ) )
				->count();
		}

		return $count;
	}

	public function fetch_pid_votes( $praise, $openid = "", $pid = "", $begin_time = 0, $end_time = 0 )
	{
		$count = 0;

		if( $end_time - $begin_time > 0 ){
			$count	=	$this->where( "openid = '%s' AND pid = '%d' AND praise = '%d' AND updated_time > %d AND updated_time < %d", array( $openid, $pid, $praise, $begin_time, $end_time ) )
				->count();
		}else if( $end_time - $begin_time < 0 && $begin_time == 0 ){
			$count	=	$this->where( "openid = '%s' AND pid = '%d' AND praise = '%d' AND updated_time > %d", array( $openid, $pid, $praise, $begin_time ) )
				->count();
		}else if( $end_time === 0 && $begin_time === 0 ){
			$count = $this->where( "openid = '%s' AND pid = '%d' AND praise = '%d' ", array($openid, $pid, $praise) )->count();
		}

		return $count;
	}

	public function fetch_praise_votes( $praise, $openid = "" )
	{
		$count = $this->where( "openid = '%s' AND praise = %d", array($openid, $praise))->count();
		return $count;
	}
}
?>
